<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="100px" :rules="rules" ref="form" :model="crud.order"
                 :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务日期">
                <el-date-picker
                  v-model="crud.order.busDate"
                  type="date"
                  size="small"
                  :disabled="crud.order.orderStatus==='PASS'"
                  class="date-item"
                  style="width: 100%;"
                  format="yyyy - MM - dd"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据编号" prop="code">
                <el-input v-model="crud.order.code" :disabled="true" placeholder="请输入单号"></el-input>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="供应商" prop="customerId">
                <zSelect :value.sync="crud.order.customerId" :showName="crud.order.customerName"
                         url="api/dropDown/basCustomerList"
                         :params="{isContact:'1,2'}" @change="updateCustom"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="供应商编码" prop="customerCode">
                <el-input :disabled="true" v-model="crud.order.customerCode"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="销售部门" prop="deptId">
                <zSelect :value.sync="crud.order.deptId" :label="crud.order.deptName"
                        :showName="crud.order.deptName"
                         url="api/dropDown/childSysDeptList"
                         style="width:  100%" @change="changeDept"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务员" prop="userId">
                <zSelect :value.sync="crud.order.userId" :showName="crud.order.userName" url="api/dropDown/sysUserList"
                         :params="userParams"
                         style="width:  100%;"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="付款类型" prop="type">
                <el-select v-model="crud.order.type" class="filter-item" clearable placeholder="状态" size="small"
                           style="width: 100%;">
                  <el-option
                    v-for="item in dict.t_finance_supplier_payment_type"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="付款总额">
                <el-input-number size="medium" :disabled="true" style="width:100%" v-model="crud.order.taxAmount"
                                 :precision="2"
                                 :step="0.1"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="本次核销金额">
                <el-input-number size="medium" :disabled="true" style="width:100%" v-model="crud.order.curCancelAmount"
                                 :precision="2"
                                 :step="0.1"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="已核销金额">
                <el-input-number size="medium" :disabled="true" style="width:100%" v-model="crud.order.cancelAmount"
                                 :precision="2"
                                 :step="0.1"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="未核销金额">
                <el-input-number size="medium" :disabled="true" style="width:100%"
                                 v-model="crud.order.unCancelAmount"
                                 :precision="2"
                                 :step="0.1"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="尾差">
                <el-input-number size="medium" :disabled="true" style="width:100%" v-model="crud.order.tailAmount"
                                 :precision="2"
                                 :step="0.1"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
<!--            <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="6">-->
<!--              <el-form-item label="银行账户" prop="bankAccount">-->
<!--                <el-input v-model="crud.order.bankAccount" :disabled="true" />-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="6">
              <el-form-item label="状态" prop="orderStatus">
                <el-select :disabled="true" v-model="crud.order.orderStatus" class="filter-item" clearable
                           placeholder="请选择状态" size="small"
                           style="width: 100%;">
                  <el-option
                    v-for="item in dict.common_order_status"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8" :lg="12" :xl="12">
              <el-form-item label="备注">
                <el-input v-model="crud.order.remark"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="可分配金额">
                <el-input :value="getCanUseAmount" readonly :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="6">
              <el-form-item label="供应商银行账户" prop="supplierBankAccount">
                <el-input v-model="crud.order.supplierBankAccount" disabled />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="6">
              <el-form-item label="供应商开户名" prop="supplierBankAccountName">
                <el-input v-model="crud.order.supplierBankAccountName" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="6">
              <el-form-item label="供应商开户银行" prop="supplierBankOpenName">
                <el-input v-model="crud.order.supplierBankOpenName" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="总应付">
                <el-input v-model="crud.order.supplierPay" readonly :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!--   操作栏   -->
      <div>
        <el-button
          slot="left"
          class="filter-item"
          @click="addDetail"
          type="primary"
          size="mini"
        >
          添加
        </el-button>
        <el-button slot="right" class="filter-item" :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'" size="mini"
                   type="primary" @click="submit()">
          保存
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="success"
                   :disabled="crud.order.orderStatus !== 'SAVE'"
                   :loading="crud.passLoading" @click="crud.doDetailPassOrReject('PASS',id)">
          审核
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="info" :loading="crud.rejectLoading"
                   :disabled="crud.order.orderStatus !== 'PASS'" @click="crud.doDetailPassOrReject('REJECT',id)">
          反审
        </el-button>
        <el-button
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView"
          :disabled="$route.params.id == 'add'"
        >打印</el-button>
        <el-button
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
          :disabled="$route.params.id == 'add'"
        >打印预览</el-button>
        <el-button slot="right" class="filter-item" size="mini" type="info" @click="getFinanceCustomerReceiptOrder()"
                   :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'">
          申请抽单
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="info" :loading="crud.rejectLoading"
                   :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                   @click="addBankData">
          添加银行
        </el-button>
        <el-button
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.refresh()"
        >刷新</el-button>
      </div>
      <el-table ref="bank-table" stripe border v-loading="crud.loading" :row-class-name="crud.tableRowClassName"
                :data="crud.order.bankList"
                size="small" style="width: 100%;"
                :show-summary="true"
                :summary-method="sumBank"
                sortable="custom">
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
        <el-table-column width="160" :render-header="crud.renderHeader" v-if="false" prop="bankName" label="银行名称"/>
        <el-table-column width="160" :render-header="crud.renderHeader" v-if="columns.visible('bankId')" prop="bankId" label="银行">
          <template slot-scope="{row,$index}">
            <zSelect :value.sync="row.bankId"
                     :showName="row.bankName"
                     :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                     url="api/basBank/getBasBanksById"
                     :params="{sort: 'seq desc'}"
                     style="width:  100%;"
                     @change="bankSelectFunc($index,$event)"
            />
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('bankOpenBranch')"
                         prop="bankOpenBranch" label="银行支行"
                         width="200"/>
        <el-table-column width="160" :render-header="crud.renderHeader" v-if="columns.visible('bankAccount')" prop="bankAccount"
                         label="银行账户"/>
        <el-table-column width="160" :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount"
                         label="金额">
          <template slot-scope="{row}">
            <el-input-number
              :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
              style="width:100%"
              v-model="row.taxAmount"
              :precision="2"
              :step="0.1"
              @change="changeBankAmount"
            />
          </template>
        </el-table-column>
        <el-table-column  :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注"/>
        <el-table-column width="160" :render-header="crud.renderHeader" v-if="columns.visible('balanceAmount')" prop="balanceAmount"
                         label="银行余额"/>
        <el-table-column :render-header="crud.renderHeader" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <el-button
              slot="reference" class="el-icon-delete opration_icon_btn"
              :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
              style="border: none;width: auto;height: auto"
              @click="bankDelAddRow(scope.$index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <hr style="margin: 20px 0">
      <!--      :summary-method="crud.getSummaries"-->
      <el-table ref="table" stripe border v-loading="crud.loading" :row-class-name="crud.tableRowClassName"
                :data="crud.order.orderList"
                size="small" style="width: 100%;"
                :show-summary="true"
                :summary-method="sumOrder"
                sortable="custom"
                @sort-change="crud.sortChange">
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('busDate')" prop="busDate"
                         label="业务日期"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('sourceType')" prop="sourceType"
                         label="单据类型">
          <template slot-scope="{row}">
            <span v-for="item in dict.t_payment_order_type" v-if="item.value == row.sourceType">
              {{ item.label }}
            </span>
          </template>
        </el-table-column>
        <el-table-column width="120" :render-header="crud.renderHeader" v-if="columns.visible('sourceCode')"
                         prop="sourceCode" label="单据编号"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount"
                         label="金额"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('cancelAmount')" prop="cancelAmount"
                         label="已核销金额"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('unCancelAmount')"
                         prop="unCancelAmount" label="未核销金额"/>
        <el-table-column width="180" :render-header="crud.renderHeader" v-if="columns.visible('curCancelAmount')"
                         prop="curCancelAmount" label="本次核销金额">
          <template slot-scope="{row}">
            <span>
              <el-input-number
                style="width:100%"
                :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                v-model="row.curCancelAmount"
                :precision="2"
                :step="0.1"
                @change="changeOrderCurCancelAmount"
              ></el-input-number>
            </span>
          </template>
        </el-table-column>
        <el-table-column width="180" :render-header="crud.renderHeader" v-if="columns.visible('tailAmount')"
                         prop="tailAmount" label="尾差">
          <template slot-scope="{row}">
            <span>
              <el-input-number
                style="width:100%"
                :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                v-model="row.tailAmount"
                :precision="2"
                :step="0.1"
                @change="changeOrderTailAmount"
              ></el-input-number>
            </span>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注"/>
        <el-table-column :render-header="crud.renderHeader" label="操作" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button
              slot="reference" class="el-icon-delete opration_icon_btn"
              :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
              style="border: none;width: auto;height: auto"
              @click="delAddRow(scope.$index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
    <el-dialog
      title="请选择打印模板"
      :visible.sync="crud.printConfig.pringDialog"
      width="30%"
      v-dialogDrag
    >
      <jPrintConfig groupId="financeSupplierPayment"
                    v-if="crud.printConfig.pringDialog"
                    @getPrintId="crud.detailedPrint"
                    :isPreview="crud.printConfig.isPreview"
      ></jPrintConfig>
    </el-dialog>
    <el-dialog title="申请抽单" :top="orderTop" :visible.sync="showReceiptOrder" width="80%">
      <div>
        <el-form size="small" label-width="100px" :model="receiptOrderQuery">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据编号">
                <el-input v-model="receiptOrderQuery.sourceCode" placeholder="支持模糊查询"></el-input>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据类型">
                <el-select v-model="receiptOrderQuery.sourceType" class="filter-item" clearable placeholder="单据类型"
                           size="small"
                           style="width: 100%;">
                  <el-option v-for="item in dict.t_payment_order_type" :key="item.id" :label="item.label"
                             :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="备注">
                <el-input v-model="receiptOrderQuery.remark" placeholder="单行输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户">
                <el-input v-model="receiptOrderQuery.customerKeyword" placeholder="单行输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-button type="primary" @click="receiptOrderSizeChangeHandler()">搜索</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-table ref="table" stripe border height="480" :row-class-name="crud.tableRowClassName"
                v-loading="receiptOrderLoading"
                :data="receiptOrderTableData" size="small" style="width: 100%;"
                :summary-method="crud.sumRow"
                show-summary
                @selection-change="receiptOrderSelection">
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('busDate')" prop="busDate"
                         sortable
                         :sort-orders="['descending', 'ascending', null]"
                         sort-change="sort"
                         label="业务日期"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('sourceType')" prop="sourceType"
                         label="单据类型">
          <template slot-scope="{row}">
            <span v-for="item in dict.t_payment_order_type" v-if="item.value == row.sourceType">
              {{ item.label }}
            </span>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('sourceCode')" prop="sourceCode"
                         sortable
                         label="单据编号"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerName')" prop="customerName"
                         label="供应商名称"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount"
                         sortable
                         label="金额"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('cancelAmount')" prop="cancelAmount"
                         sortable
                         label="已核销金额"/>
        <el-table-column :render-header="crud.renderHeader"
                         sortable
                         v-if="columns.visible('unCancelAmount')"
                         prop="unCancelAmount" label="未核销金额"/>
        <el-table-column :render-header="crud.renderHeader" sortable v-if="columns.visible('curCancelAmount')"
                         prop="curCancelAmount" sortable label="本次核销金额"/>
        <el-table-column :render-header="crud.renderHeader" sortable v-if="columns.visible('remark')" prop="remark" label="备注"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="showReceiptOrder = false">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="receiptOrderConfirm">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import financeSupplierPayment, {orderDetail} from '@/api/erp/financeSupplierPayment'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import jtgSelectPlus from '@/components/select/JtgSelectPlus'
import money from '@/components/money/money'
import {getBusTime} from '@/utils/index'
import {Notification, Pagination} from "element-ui";
import jPrintConfig from '@/components/jPrintConfig/jPrintConfig'
import {getSupplierPay} from "../../../api/erp/financeSupplierPayment";
// crud交由presenter持有
const defaultCrud = CRUD({
  title: '付款单明细',
  order: {
    unCancelAmount: 0.00,
    taxAmount: 0.00,
    busDate: getBusTime(),
    bankList: [],
    orderList: []
  },
  params() {
    const href = location.href.split('/')
    return {
      id: href[href.length - 1] == 'add' ? 0 : href[href.length - 1],
    }
  },
  url: 'api/financeSupplierPayment/detail', sort: 'id,desc', crudMethod: {...financeSupplierPayment}
})
const defaultForm = {
  id: null,
  orderId: null,
  goodsId: null,
  goodsCode: null,
  goodsName: null,
  barcode: null,
  boxBarcode: null,
  helpSign: null,
  model: null,
  goodsBrandId: null,
  goodsBrandCode: null,
  goodsBrandName: null,
  goodsTypeId: null,
  goodsTypeCode: null,
  goodsTypeName: null,
  goodsTagId: null,
  goodsTagCode: null,
  goodsTagName: null,
  taxId: null,
  taxCode: null,
  taxName: null,
  taxRate: null,
  firstUnitId: null,
  firstUnitCode: null,
  firstUnitName: null,
  firstUnitCount: null,
  effectGoodsCount: null,
  cutOffGoodsCount: null,
  taxPrice: null,
  noTaxPrice: null,
  taxBoxPrice: null,
  noTaxBoxPrice: null,
  seq: null,
  remark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null
}
export default {
  name: 'financeSupplierPaymentDetail',
  components: {pagination, crudOperation, rrOperation, udOperation, money, jtgSelectPlus, "el-pagination": Pagination, jPrintConfig},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['t_payment_order_type', 't_finance_supplier_payment_type', 't_buy_order_buy_channel', 't_finance_customer_receipt_type', 'common_order_status'],
  data() {
    return {
      orderAmount: null,
      allBankAmount: null,
      distributionAmount: null,
      copyForm: null,
      id: null,
      showReceiptOrder: false,
      permission: {
        add: ['admin', 'financeSupplierPaymentDetail:add'],
        edit: ['admin', 'financeSupplierPaymentDetail:edit'],
        del: ['admin', 'financeSupplierPaymentDetail:del'],
        import: ['admin', 'financeSupplierPaymentDetail:import'],
        export: ['admin', 'financeSupplierPaymentDetail:export'],
        copy: ['admin', 'financeSupplierPaymentDetail:copy'],
        upload: ['admin', 'financeSupplierPaymentDetail:upload'],
        download: ['admin', 'financeSupplierPaymentDetail:download'],
      },
      rules: {
        customerId: [
          {required: true, message: '供应商不能为空', trigger: 'blur'}
        ],
        deptId: [
          {required: true, message: '销售部门不能为空', trigger: 'blur'}
        ],
        userId: [
          {required: true, message: '业务员不能为空', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '付款类型不能为空', trigger: 'blur'}
        ]
      },
      addRowData: {
        isSelected: true,
        id: null,
        orderId: null,
        goodsId: null,
        goodsCode: null,
        goodsName: null,
        barcode: null,
        boxBarcode: null,
        helpSign: null,
        model: null,
        goodsBrandId: null,
        goodsBrandCode: null,
        goodsBrandName: null,
        goodsTypeId: null,
        goodsTypeCode: null,
        goodsTypeName: null,
        goodsTagId: null,
        goodsTagCode: null,
        goodsTagName: null,
        taxId: null,
        taxCode: null,
        taxName: null,
        taxRate: null,
        firstUnitId: null,
        firstUnitCode: null,
        firstUnitName: null,
        firstUnitCount: null,
        effectGoodsCount: null,
        cutOffGoodsCount: null,
        taxPrice: null,
        noTaxPrice: null,
        taxBoxPrice: null,
        noTaxBoxPrice: null,
        seq: null,
        remark: null,
        createUserId: null,
        createUserCode: null,
        createUserName: null,
        createTime: null,
        updateUserId: null,
        updateUserCode: null,
        updateUserName: null,
        updateTime: null
      },
      productList: [],
      userParams: {
        deptId: null
      },
      bankData: [],// 银行数据,
      receiptOrderQuery: {
        customerId: this.crud.order.customerId
      },// 收款单单据查询条件
      pageable: {
        // 页码
        page: 1,
        // 每页数据条数
        size: 999,
        // 总数据条数
        total: 0
      },  // 收款单单据翻页
      receiptOrderTableData: [],// 收款单单据明细
      receiptOrderLoading: false, //
      orderTop: "0.2vh",
      bankList: [],
      bankListParams: {id: 0},
      saleUrl: "",
      bankListLoading: false
    }
  },
  // destroyed() {
  //   this.crud.setItemInfo("financeSupplierPaymentDetail_add")
  // },

  created() {
    // if (this.$route.params.id == 'add') {
    //   if (this.crud.getItemInfo("financeSupplierPaymentDetail_add")) {
    //     return false
    //   }

      this.crud.order = {
        unCancelAmount: 0.00,
        busDate: getBusTime(),
        bankList: [],
        orderList: [],
        supplierPay: null
      }
      if(this.crud.order.busDate)this.crud.order.busDate= new Date().toISOString().split('T')[0]
      console.log(this.crud.order.busDate)
      this.copyForm=Object.assign({},this.crud.order)
    // }
  },
  computed:{
    //获取可分配金额=银行列表总金额-（抽单）（总本次核销金额+总尾差）
    getCanUseAmount(){
      return (Number(this.allBankAmount) + Number(this.orderAmount)).toFixed(2)
    },
  },
  activated() {
    console.log('=======')
    //获取上次进入Id
    const id = sessionStorage.getItem(this.$options.name + 'Id')
    //记录本次进入的Id
    sessionStorage.setItem(this.$options.name+'Id',this.$route.params.id)
    if(id !== this.$route.params.id){
      if(this.$route.params.id === 'add'){
        this.$set(this.crud,'order',Object.assign({},this.copyFrom))
        this.$set(this.crud.order,'orderList',[])
        this.$set(this.crud.order,'bankList',[])
        this.crud.data = []
        // this.$set(this.crud,'data',[])
      }else if(this.$route.params.id.indexOf('copy') !== -1){
        const copyId = this.$route.params.id.split('=')[1]
        this.crud.toGetCopyInfo(copyId)
      }else {
        this.crud.params.id = this.$route.params.id
        this.crud.refresh()
      }
    }
  },
  beforeUpdate() {
    if (this.$route.params.id != 'add') {
      this.id = this.$route.params.id
      this.crud.order.id = this.id
    }
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    [CRUD.HOOK.afterRefresh](crud, form) {
      if (this.$route.params.id == 'add') {
        crud.order = {
          curCancelAmount: 0.00,
          busDate: getBusTime(),
          bankList: [],
          orderList: []
        }
      } else {
        this.crud.order.curCancelAmount = 0.00
        if (this.crud.order.orderList) {
          for (let i = 0; i < this.crud.order.orderList.length; i++) {
            this.crud.order.curCancelAmount += this.crud.order.orderList[i].curCancelAmount
          }
        }
      }
    },
    addDetail(){
      if(this.$route.params.id !== 'add')
        this.$router.replace({ path: '/redirect/finance/financeSupplierPaymentDetail/add' })
    },
    getInfo(e) {
      this.crud.order.contactPhone = e.contactPhone
      this.crud.order.deptId = e.deptId
      this.crud.order.userId = e.userId
    },
    getTime(date = new Date()) {
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      h = h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      var second = date.getSeconds();
      second = second < 10 ? ('0' + second) : second;
      // +' '+h+':'+minute+':'+second;
      return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
    },
    delAddRow(i) {
      if (this.$route.params.id !== 'add') {
        this.$confirm('此操作将直接删除此条产品记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.order.orderList.splice(i, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.crud.order.orderList.splice(i, 1)
      }
      this.changeOrderCurCancelAmount()
      this.changeOrderTailAmount()
    },
    // 删除银行
    bankDelAddRow(i) {
      this.crud.order.bankList.splice(i, 1)
      this.sumAmount()
    },
    // 保存
    submit() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        const bank_rules = [
          {name: '银行', value: 'bankId'},
          {name: '金额', value: 'taxAmount'}
        ]
        let bankList = this.crud.order.bankList
        if (!this.tableRules(bankList, bank_rules, "请选择银行支付")) {
          return;
        }
        this.save()
      })
    },
    tableRules(list, rules, nullMsg) {
      let flag = true
      if (list === null || list.length === 0) {
        Notification.error({title: nullMsg})
        return false
      }
      rules.forEach(rule => {
        for (let i = 0; i < list.length; i++) {
          if (list[i][rule.value] === undefined || list[i][rule.value] == null || list[i][rule.value] === '') {
            Notification.error({title: '序号【' + (i + 1) + '】' + rule.name + '不能为空'})
            flag = false
            break
          }
        }
      })
      return flag
    },
    //保存
    save() {
      let that = this
      that.crud.loadingOpen()
      // this.crud.order.detailList = this.crud.data
      let params = this.crud.order
      financeSupplierPayment.add(params).then(res => {
        if (res.success) {
          this.crud.order = res.data.order
          let id = this.crud.order.id
          if (this.$route.params.id == 'add') {
            this.$router.replace('/redirect/finance/financeSupplierPaymentDetail/'+id)
          }
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          that.crud.loadingClose()
        } else {
          that.crud.loadingClose()
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }

      }).catch((res) => {
        that.crud.loadingClose()
      })
    },
    // 添加银行数据
    addBankData() {
      let bankItem = {
        bankId: '',
        bankName: '',
        bankOpenBranch: '',
        bankAccount: '',
        balanceAmount: 0.00,
        taxAmount: 0.00,
        remark: '',
      }
      this.crud.order.bankList.push(bankItem);
    },
    // 选择银行之后
    bankSelectFunc(idx, selectedBank) {
      const {id, name, bankOpenBranch, bankAccount, balanceAmount, taxAmount, remark} = selectedBank;
      this.crud.order.bankList[idx].bankId = id
      this.crud.order.bankList[idx].bankName = name
      this.crud.order.bankList[idx].bankOpenBranch = bankOpenBranch
      this.crud.order.bankList[idx].bankAccount = bankAccount
      this.crud.order.bankList[idx].balanceAmount = balanceAmount
      this.crud.order.bankList[idx].remark = remark
    },
    // 选中收款单单据
    receiptOrderSelection(rows) {
      if (rows) {
        this.selectedRows = rows
        this.crud.selectionChangeHandler(rows)
      }
    },
    receiptOrderSizeChangeHandler() {
      this.pageable.page = 1
      this.getFinanceCustomerReceiptOrder()
    },
    receiptOrderPageChangeHandler(e) {
      this.pageable.page = e
      this.getFinanceCustomerReceiptOrder()
    },
    // 收款单单据弹窗点击确定
    receiptOrderConfirm(e) {
      let curCancelAmount = 0.00
      let cancelAmount = 0.00
      let unCancelAmount = 0.00
      let tailAmount = 0.00
      this.selectedRows.forEach(row => {
        const sourceCode = row.sourceCode
        let flag = this.checkSourceCode(row)
        if (flag) {
          this.$message.error("单据编号已存在，请核查！")
          return false
        }
        let item = {
          busDate: row.busDate,
          sourceId: row.sourceId,
          sourceType: row.sourceType,
          sourceCode: sourceCode,
          taxAmount: row.taxAmount,
          cancelAmount: row.cancelAmount,
          unCancelAmount: row.unCancelAmount,
          curCancelAmount: row.unCancelAmount,
          tailAmount: 0.00,
          remark: row.remark
        }
        this.crud.order.orderList.push(item)
        curCancelAmount += item.curCancelAmount
        cancelAmount += row.cancelAmount
        unCancelAmount += row.unCancelAmount
        tailAmount += row.tailAmount
      })
      this.crud.order.curCancelAmount = curCancelAmount
      // this.crud.order.cancelAmount = cancelAmount
      this.crud.order.tailAmount = tailAmount
      // this.crud.order.unCancelAmount = this.crud.order.taxAmount - cancelAmount

      this.showReceiptOrder = false
    },
    checkSourceCode(row) {
      let flag = false
      if (this.crud.order.orderList) {
        for (let i = 0; i < this.crud.order.orderList.length; i++) {
          if (this.crud.order.orderList[i].sourceCode === row.sourceCode) {
            flag = true
          }
        }
      }
      return flag
    },
    // 收款单单据列表
    getFinanceCustomerReceiptOrder() {
      let params = {
        ...this.receiptOrderQuery,
        ...this.pageable
      }
      console.log(params)
      this.receiptOrderLoading = true
      orderDetail(params).then(res => {
        this.receiptOrderTableData = res.data.content
        this.showReceiptOrder = true
        this.receiptOrderLoading = false
      }).finally(() => {
        this.receiptOrderLoading = false
      })
    },
    updateCustom(e) {
      console.log(e)
      this.bankListParams.id = e.id
      this.receiptOrderQuery.customerId = e.id
      this.crud.order.customerName = e.name
      this.crud.order.deptId = e.deptId
      this.crud.order.deptName = e.deptName
      this.crud.order.userId = e.userId
      this.crud.order.userName = e.userName
      this.crud.order.customerCode = e.code
      this.crud.order.bankAccount = e.bankAccount
      // this.crud.order.supplierPay = e.supplierPay;
      // console.log(this.crud.order.supplierPay)
      this.crud.order.supplierBankAccount = e.bankAccount
      this.crud.order.supplierBankAccountName = e.bankAccountName
      this.crud.order.remark = e.remark

      //总应付
      const supplierId = this.receiptOrderQuery.customerId
      const that = this
      getSupplierPay({supplierId: supplierId}).then( res=>{
        if (res.status === 200){
          console.log('=========')
          console.log(res.data)
          that.crud.order.supplierPay = res.data
          that.$message.success(res.msg)
        }else {
          that.$message.error(res.msg)
        }
      })
    },
    sumBank({columns, data}) {
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (column.property == 'taxAmount' || column.property == 'balanceAmount') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0).toFixed(2);
          if (column.property == 'taxAmount'){
            this.allBankAmount = sums[index]
            console.log(this.allBankAmount)
          }

        }
      });
      return sums
    },
    sumOrder({columns, data}) {
      const sums = []
      let a = 0
      let b = 0
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (column.property === 'taxAmount'
          || column.property === 'cancelAmount'
          || column.property === 'unCancelAmount'
          || column.property === 'curCancelAmount'
          || column.property === 'tailAmount'
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0).toFixed(2);

          if (column.property == 'curCancelAmount' ){
            a = sums[index]
          }
          else if (column.property == 'tailAmount'){
            b = sums[index]
          }

        }
        // if (column.property === 'cancelAmount') {
        //   this.crud.order.cancelAmount = sums[index]
        // }
        // if (column.property === 'unCancelAmount') {
        //   this.crud.order.unCancelAmount = sums[index]
        // }
        // if (column.property === 'curCancelAmount') {
        //   this.crud.order.curCancelAmount = sums[index]
        // }
        // if (column.property === 'tailAmount') {
        //   this.crud.order.tailAmount = sums[index]
        // }
      });
      this.orderAmount = Number(a) + Number(b)
      console.log(this.orderAmount)
      return sums
    },
    changeOrderCurCancelAmount() {
      let curCancelAmount = 0.00
      for (let i = 0; i < this.crud.order.orderList.length; i++) {
        curCancelAmount += this.crud.order.orderList[i].curCancelAmount
      }
      this.crud.order.curCancelAmount = curCancelAmount
      // this.crud.order.unCancelAmount = this.crud.order.taxAmount - this.crud.order.curCancelAmount
    },
    changeBankAmount(e) {
      this.sumAmount()
    },
    sumAmount() {
      this.crud.order.taxAmount = 0.00
      for (let i = 0; i < this.crud.order.bankList.length; i++) {
        this.crud.order.taxAmount += this.crud.order.bankList[i].taxAmount
      }
      this.crud.order.unCancelAmount = this.crud.order.taxAmount - this.crud.order.cancelAmount
    },
    changeOrderTailAmount(e) {
      this.crud.order.tailAmount = 0.00
      for (let i = 0; i < this.crud.order.orderList.length; i++) {
        this.crud.order.tailAmount += this.crud.order.orderList[i].tailAmount
      }
    },
    changeDept(e) {
      const {id} = e
      this.userParams.deptId = id
    }
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
